<template>
  <div v-loading="loadBg"
       element-loading-text="拼命加载中"
       element-loading-background="rgba(0, 0, 0, 1)"
       element-loading-spinner="el-icon-loading">
    <div class="login-wrapper"
         v-if="mainTechnicianBoolen"
         :style="
        indexMainData?.loginBackgroundImg
          ? {
              'background-image':
                'url(' + indexMainData?.loginBackgroundImg + ')'
            }
          : { 'background-image': 'url(' + backgrounds + ')' }
      ">
      <div :class="[
          'copyrightStatement',
          { 'hidden-sm-and-down': styleResponsive }
        ]"
           v-if="isMainOnline">
        电话 :{{ indexMainData?.phone ? indexMainData?.phone : '***********' }}
        │ 地址 :
        {{ indexMainData?.address ? indexMainData?.address : '***********' }} │
        版权信息∶{{
          indexMainData?.copyrightInfo
            ? indexMainData?.copyrightInfo
            : '*************'
        }}
        │ <span v-if="indexMainData?.publicNetworkRecordNumber?true:false">
          京公网备案号︰<span @click="publicNetworkRecordNumberFn(indexMainData?.publicNetworkRecordNumber?'https://beian.mps.gov.cn/#/query/webSearch':false)">{{
          indexMainData?.publicNetworkRecordNumber

            ? indexMainData?.publicNetworkRecordNumber

            : '*************'
        }}</span>
        </span>
        |<span v-if="indexMainData?.recordNumber?true:false">
          备案号︰<span @click="recordNumberFn(indexMainData?.recordNumber?'https://beian.miit.gov.cn/':false)">
            {{
          indexMainData?.recordNumber


            ? indexMainData?.recordNumber


            : '*************'
        }}
          </span>
        </span>
        | 客服二维码
        <img class="serviceQrCode"
             :src="
            indexMainData?.customerServiceQrCode
              ? indexMainData?.customerServiceQrCode
              : require('/src/assets/images/微信图_09.png')
          "
             alt="" />
      </div>
      <el-card shadow="always"
               class="login-card">
        <div class="login-cover"
             :style="
            indexMainData?.loginBackgroundImgTwo
              ? {
                  'background-image':
                    'url(' + indexMainData?.loginBackgroundImgTwo + ')'
                }
              : { 'background-image': 'url(' + backgroundsTwo + ')' }
          ">
        </div>
        <div :class="['siteIcon', { 'hidden-sm-and-down': styleResponsive }]"
             :style="
            indexMainData?.loginLeftLogo
              ? {
                  'background-image':
                    'url(' + indexMainData?.loginLeftLogo + ')'
                }
              : ''
          ">
        </div>

        <div class="login-body">
          <h1 class="login-title">欢迎登录</h1>
          <h4 class="login-subtitle">WELCOME TO LOGIN</h4>
          <el-form ref="form"
                   size="large"
                   :model="form"
                   :rules="rules">
            <el-form-item prop="username">
              <el-input clearable
                        v-model="form.username"
                        @keyup.enter.native="submit"
                        placeholder="请输入登录账号"
                        prefix-icon="el-icon-user" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input show-password
                        v-model="form.password"
                        @keyup.enter.native="submit"
                        placeholder="请输入登录密码"
                        prefix-icon="el-icon-lock" />
            </el-form-item>
            <el-form-item prop="code">
              <div class="login-captcha-group">
                <el-input clearable
                          v-model="form.code"
                          placeholder="请输入验证码"
                          @keyup.enter.native="submit"
                          prefix-icon="el-icon-_vercode" />
                <div class="login-captcha"
                     @click="changeCaptcha">
                  <img v-if="captcha"
                       :src="captcha" />
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="form.remember">记住密码</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button size="large"
                         type="primary"
                         round
                         :loading="loading"
                         style="width: 70%"
                         @click="submit">
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
    <technician :indexData="indexData"
                v-if="technicianBoolen"
                :isOnLine="isOnLine"></technician>
  </div>
</template>

<script>
// 获取站点info
import Cookies from 'js-cookie';
import { getUserRoleName } from '@/api/updateVersion';
import { platformConfigDetail } from '@/api/platformSettings/index';
import { getSiteDomainName } from '@/api/site/index';
import technician from './components/technicianEnd.vue';
import I18nIcon from '@/layout/components/i18n-icon.vue';
import { getToken } from '@/utils/token-util';
import { login, getCaptcha } from '@/api/login';
import { sitePlatformConfigDetail } from '@/api/basicConfiguration/basicConfiguration/index';
export default {
  name: 'Login',
  components: { technician },
  data () {
    return {
      loadBg: true,
      // 登录框方向, 0居中, 1居右, 2居左
      direction: 0,
      // 加载状态
      loading: false,
      // 表单数据
      form: {
        username: '',
        password: '',
        remember: false,
        code: ''
      },
      // 验证码base64数据
      captcha: '',
      //   验证码内容, 实际项目去掉
      text: '',
      siteId: '',
      isOnLine: false,
      isMainOnline: false,
      indexData: null,
      indexMainData: null,
      backgrounds: require('/src/assets/images/网络登录.jpg'),
      backgroundsTwo: require('/src/assets/images/网络登录_07.png'),
      loginLeftLogo: require('/src/assets/images/微信图片_8.png'),
      mainTechnicianBoolen: false,
      technicianBoolen: false,
      currentSoftwareStatus: ''
    };
  },

  computed: {
    // 表单验证规则
    rules () {
      return {
        username: [
          {
            required: true,
            message: this.$t('login.username'),
            type: 'string',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: this.$t('login.password'),
            type: 'string',
            trigger: 'blur'
          }
        ]
      };
    },
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    }
  },

  created () {
    // let host = 1
    let host = window.location.host;
    let origin = window.location.origin;

    this.querys();
    // 1 :总端 2:商家端 3：代理端  ———— 默认登录背景+左侧图片
    //   this.backgrounds = host=='dspkk.weijuyunke.com' ? require('/src/assets/allBj.png') : host=='oemkk.weijuyunke.com' ? require('/src/assets/loginBj.jpg') : require('/src/assets/agentBj.jpg')
    //   this.leftIcons = host=='dspkk.weijuyunke.com' ? require('/src/assets/allLeft2.png') : host=='oemkk.weijuyunke.com' ? require('/src/assets/leftIcon2.png') : require('/src/assets/agentLeft.jpg')
    //     console.log("window==========",'http://'+host.split(':')[0])
    if (getToken()) {
      this.goHome();
    } else {
      this.changeCaptcha();
    }
    this.getCookie();
  },
  methods: {
    publicNetworkRecordNumberFn (url) {
      if (url) {
        window.open(url, '_blank');
        // window.location.href = url;
      }
    },
    recordNumberFn (url) {
      if (url) {
        window.open(url, '_blank');
        // window.location.href = url;
      }
    },
    /* 提交 */
    async submit () {
      if (this.form.remember) {
        console.log('存数据=============');
        Cookies.set('zhuUsername', this.form.username, { expires: 600 });
        Cookies.set('zhuPassword', this.form.password, { expires: 600 });
        Cookies.set('zhuRemember', this.form.remember, { expires: 600 });
      } else {
        // 否则移除
        Cookies.remove('zhuUsername');
        Cookies.remove('zhuPassword');
        Cookies.remove('zhuRemember');
      }

      const getRoleName = await getUserRoleName({
        username: this.form.username
      });
      console.log(getRoleName);

      if (getRoleName.roleName !== '主站') {
        this.$message.error('当前不是主站账号');
        return;
      }

      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }

        if (this.form.code.toLowerCase() !== this.text) {
          this.$message.error('验证码错误');
          return;
        }
        this.loading = true;
        login(this.form)
          .then((msg) => {
            this.loading = false;
            this.$message.success(msg);
            this.goHome();
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });

        this.loading = true;
      });
    },
    async querys () {
      const result = await getSiteDomainName({
        // siteDomainName: 'yy.kunda5518.xyz'
        // siteDomainName: 'yjyksaas.admin168.net'
        // siteDomainName: ''
        // siteDomainName: window.location.host
      }).catch(() => { });
      console.log(result);
      if (result) {
        this.siteId = result.id;

        this.init();
      } else {
        this.mainPlatform();
      }
    },
    async init () {
      this.technicianBoolen = true;
      // 查询回显
      sitePlatformConfigDetail({ siteId: this.siteId })
        .then((msg) => {
          console.log(msg);
          if (msg) {
            this.indexData = msg;

            localStorage.setItem('indexData', JSON.stringify(this.indexData)); // 存储 “系统图标等”
            // let item = JSON.parse(localStorage.getItem('indexData'))
            this.isOnLine =
              this.indexData?.copyrightInfo ||
                this.indexData.publicNetworkRecordNumber ||
                this.indexData.recordNumber ||
                this.indexData.telephone ||
                this.indexData.phone ||
                this.indexData.address
                ? true
                : false;
            // 设置动态标题
            document.title = this.indexData.sysName;
            // 设置动态link图标（icon)
            var link =
              document.querySelector("link[rel*='icon']") ||
              document.createElement('link');
            link.type = 'image/x-icon';
            link.rel = 'shortcut icon';
            link.href = this.indexData.browserLogo
              ? this.indexData.browserLogo
              : require('@/assets/browser1.png');
            document.getElementsByTagName('head')[0].appendChild(link);
          }
          this.loadBg = false;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },

    async mainPlatform () {
      const result = await platformConfigDetail().catch(() => { });
      console.log(result);
      this.indexMainData = result;

      this.mainTechnicianBoolen = true;
      if (this.indexMainData) {
        localStorage.setItem('indexData', JSON.stringify(this.indexMainData)); // 存储 “系统图标等”
        // let item = JSON.parse(localStorage.getItem('indexData'))
        this.isMainOnline =
          this.indexMainData?.copyrightInfo ||
            this.indexMainData?.publicNetworkRecordNumber ||
            this.indexMainData?.recordNumber ||
            this.indexMainData?.phone ||
            this.indexMainData?.address
            ? true
            : false;
        // 设置动态标题
        document.title = this.indexMainData?.sysName;
        // 设置动态link图标（icon)
        var link =
          document.querySelector("link[rel*='icon']") ||
          document.createElement('link');
        link.type = 'image/x-icon';
        link.rel = 'shortcut icon';
        link.href = this.indexMainData.browserLogo
          ? this.indexMainData.browserLogo
          : require('@/assets/browser1.png');
        document.getElementsByTagName('head')[0].appendChild(link);
        this.loadBg = false;
      } else {
        this.loadBg = false;
      }
    },
    /* 跳转到首页 */
    goHome () {
      this.$router.push(this.$route?.query?.from ?? '/').catch(() => { });
    },
    /* 更换图形验证码 */
    changeCaptcha () {
      // 这里演示的验证码是后端返回base64格式的形式, 如果后端地址直接是图片请参考忘记密码页面
      getCaptcha()
        .then((data) => {
          this.captcha = data.base64;
          // 实际项目后端一般会返回验证码的key而不是直接返回验证码的内容, 登录用key去验证, 可以根据自己后端接口修改
          this.text = data.text;
          // 自动回填验证码, 实际项目去掉这个
          //   this.form.code = this.text;
          this.$refs?.form?.clearValidate();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    getCookie () {
      console.log('取数据=============');
      const usernames = Cookies.get('zhuUsername');
      const passwords = Cookies.get('zhuPassword');
      const remembers = Cookies.get('zhuRemember');
      console.log(usernames);
      console.log(passwords);
      console.log(remembers);
      this.form.username =
        usernames === undefined ? this.form.username : usernames;
      this.form.password =
        passwords === undefined ? this.form.password : passwords;
      this.form.remember =
        remembers === undefined ? this.form.remember : Boolean(remembers);
    }
  }
};
</script>
<style lang="scss" scoped>
.login-wrapper {
  min-height: 100vh;
  box-sizing: border-box;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  //   background-image: url('/src/assets/images/网络登录.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: relative;
  .login-card {
    width: 920px;
    max-width: 100%;
    overflow: hidden;
    .siteIcon {
      //   background-image: url('/src/assets/images/网络登录_03.png');
      background-repeat: no-repeat;
      background-size: 60%;
      position: absolute;
      height: 101px;
      width: 329px;
      top: 5.5%;
      transform: translate(-57px, -8px);
      z-index: 9999;
    }
    :deep(.el-card__body) {
      padding: 0;
      height: 462px;
    }
  }
}
.copyrightStatement {
  color: #fff;
  position: absolute;
  font-size: 16px;
  bottom: 24px;
  .serviceQrCode {
    margin-left: 10px;
    vertical-align: middle;
    width: 100px;
    height: 100px;
  }
}
.login-cover {
  position: absolute;
  -webkit-box-flex: 1;
  /* z-index: -1; */
  -ms-flex: 1;
  flex: 1;
  padding: 36px 8px;
  width: 590px;
  height: 463px;
  max-width: 100%;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  background-repeat: no-repeat;
  background-position: bottom;
  background-size: cover;
  text-align: center;
  margin-left: 370px;
}

.login-body {
  width: 400px;
  flex-shrink: 0;
  padding: 32px 48px 0 48px;
  box-sizing: border-box;

  :deep(.el-checkbox) {
    height: auto;

    .el-checkbox__label {
      color: inherit;
    }
  }

  :deep(.el-input__prefix-inner > .el-icon) {
    margin-right: 12px;
    transform: scale(1.26) translateY(-1px);
  }
}

// 验证码
.login-captcha-group {
  width: 100%;
  display: flex;
  align-items: center;

  :deep(.el-input) {
    flex: 1;
  }

  .login-captcha {
    width: 108px;
    height: 40px;
    margin-left: 8px;
    border-radius: 4px;
    border: 1px solid hsla(0, 0%, 60%, 0.46);
    transition: border 0.2s;
    box-sizing: border-box;
    background: #fff;
    overflow: hidden;
    cursor: pointer;

    img {
      width: calc(100% + 4px);
      height: calc(100% + 4px);
      margin: -2px 0 0 -2px;
      display: block;
    }

    &:hover {
      border-color: hsla(0, 0%, 60%, 0.8);
    }
  }

  :deep(.el-input__prefix-inner > .el-icon) {
    transform: scale(1.16);
  }
}

// 标题
.login-title {
  color: #007af5;
  font-weight: 700;
  font-size: 26px;
  margin: 0 0 0px 0;

  font-family: 'AliPuHui';
  letter-spacing: 1.2px;
}

.login-subtitle {
  color: #333333;
  font-size: 17px;
  margin: 0;
  font-weight: 700;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
  letter-spacing: 4px;
  margin-bottom: 20px;
}
:deep(.el-icon) {
  color: #007af5;
}
/* 阿里巴巴普惠体 */
@font-face {
  font-family: 'AliPuHui';
  font-weight: 300;
  src: (
    url('//at.alicdn.com/wf/webfont/jWZHcEP2lzge/5AfKUTWZEo8W.woff2')
      format('woff2'),
    url('//at.alicdn.com/wf/webfont/jWZHcEP2lzge/Dvhs41TtRdYF.woff')
      format('woff')
  );
  font-display: swap;
}

// 二维码
.login-qrcode-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 0;
}

.login-qrcode {
  font-size: 0;
  display: inline-block;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

// 小屏幕适应
@media screen and (max-width: 680px) {
  .login-wrapper {
    padding: 0;
    display: block;
    background: #fff;

    .login-card {
      width: 100%;
      background: none;
      box-shadow: none;
      border-radius: 0;

      :deep(.el-card__body) {
        display: block;
        height: auto;
      }
    }
  }

  .login-cover {
    padding: 24px 12px 100px 12px;
    background-size: auto 100px;
  }

  .login-body {
    width: 100%;
  }
}
</style>

<style lang="scss">
html.dark .login-wrapper {
  background: #000;
  filter: brightness(0.88);
}
</style>
